import os
import sys
import time
import subprocess

import requests
from PyQt5 import QtCore
from PyQt5.Qt import *
from pywinauto import Desktop
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import json

from TWindow import TWindow
from config.global_settings import  ENTRY_DOWNLOAD_PATH, DEFAULT_WAIT,  \
    YFYS_DOWNLOAD_PATH, CHROME_PATH, ENVIRON_PATH,  gx_username, gx_password, cj_username, cj_password
from selenium.webdriver.common.by import By
from pywinauto import keyboard
from data_util.my_log import logger
import sys





class Zlyj():
    def __init__(self, share_url, arap_url, download_path, environ_list):
        """
        初始化
        :param url: 八局url
        :param download_path: 附件/发票下载路径
        :param body: 填报信息
        """
        self.xh = None
        self.ARAP_URL = arap_url
        self.filename = None
        self.download_path = download_path
        self.url = share_url
        self.environ_list = environ_list
        subprocess.Popen(
            rf'"{environ_list.get("chrome_path")}" --flag-switches-begin --flag-switches-end --remote-debugging-port=80 --user-data-dir="{environ_list.get("default_path")}"')
        # chrome  参数查询  chrome://version/
        # 向cmd发送启动浏览器服务初始化数据，默认初始化用户数据
        # subprocess.Popen(r'chrome --remote-debugging-port=8210 --user-data-dir="C:\Users\wj\AppData\Local\Google\Chrome\User Data\Default"')
        # subprocess.Popen(
        #     r'"C:\Users\wj\AppData\Local\Google\Chrome\Application\chrome.exe" --flag-switches-begin --flag-switches-end --remote-debugging-port=80 --user-data-dir="C:\Users\wj\AppData\Local\Google\Chrome\User Data\Default"')
        # subprocess.Popen(r'"C:\Users\wj\AppData\Local\Google\Chrome\Application\chrome.exe" --flag-switches-begin --flag-switches-end --remote-debugging-port=80')
        # subprocess.Popen(r'"C:\Users\wj\AppData\Local\Google\Chrome\Application\chrome.exe" --flag-switches-begin --flag-switches-end')
        options = Options()
        # options = webdriver.ChromeOptions()
        # 启动的浏览器地址
        # options.debugger_address = '127.0.0.1:80'
        options.debugger_address = '127.0.0.1:80'
        options.binary_location = environ_list.get("chrome_path")  # 手动指定使用的浏览器位置
        # options.default_directory = self.download_path
        # 手动指定使用的浏览器位置
        # prefs = {"download.default_directory": self.download_path
        #          }
        #
        # options.add_experimental_option("prefs", prefs)
        # options.add_experimental_option("debuggerAddress", '127.0.0.1:80')
        # options.to_capabilities()
        # {'browserName': 'chrome', 'version': '', 'platform': 'ANY',
        #  'goog:chromeOptions': {'debuggerAddress': '127.0.0.1:80', 'extensions': [], 'args': []}}
        # options.add_experimental_option("binaryLocation", r"C:\Program Files\Google\Chrome\Application\chrome.exe")
        # options.add_experimental_option("prefs", prefs)
        # 将浏览器配置信息进行添加
        self.driver = webdriver.Chrome(options=options, executable_path=CHROME_PATH)
        self.driver.maximize_window()

    def fill_input(self, xpath, content, timeout=DEFAULT_WAIT):
        """
        填写网页表单
        :param xpath: xpath
        :param content: 填写内容
        :param timeout: 等待元素出现时间，若超时则报错
        :return:
        """
        element = WebDriverWait(driver=self.driver, timeout=timeout, poll_frequency=0.5).until(
            EC.presence_of_element_located((By.XPATH, xpath))
        )
        self.click_element(xpath, timeout=timeout)
        element.send_keys(content)

    def click_element(self, xpath, timeout=DEFAULT_WAIT, mode='internal'):
        """
        点击元素
        :param mode: 点击元素的模式
        :param xpath: xpath
        :param timeout: 等待元素出现时间，若超时则报错
        :return: None
        """
        element_located = WebDriverWait(driver=self.driver, timeout=timeout, poll_frequency=0.5).until(
            EC.presence_of_element_located((By.XPATH, xpath))
        )
        if mode == 'internal':
            element = WebDriverWait(driver=self.driver, timeout=timeout, poll_frequency=0.5).until(
                EC.element_to_be_clickable((By.XPATH, xpath))
            )
            element.click()
        elif mode == 'external':
            self.driver.execute_script("$(arguments[0]).click()", element_located)

    def find_elements(self, xpath, timeout=DEFAULT_WAIT):
        """
        通过xpath去寻找所有元素，返回多个元素对象
        :param xpath: xpath
        :param timeout: 等待元素出现时间，若超时则报错
        :return:
        """
        elements = WebDriverWait(driver=self.driver, timeout=timeout, poll_frequency=0.5).until(
            EC.presence_of_all_elements_located((By.XPATH, xpath))
        )
        return elements

    def find_element(self, xpath, timeout=DEFAULT_WAIT):
        """
        通过xpath寻找元素，并返回元素对象
        :param xpath: xpath
        :param timeout: 等待元素出现时间，若超时则报错
        :return:
        selenium等待presence_of_element_located
        页面元素等待处理。
        """
        element = WebDriverWait(driver=self.driver, timeout=timeout, poll_frequency=0.5).until(
            EC.presence_of_element_located((By.XPATH, xpath))
        )
        return element

    def run(self):
        logger.info('账龄预警填报开始...')

        # 清空文件夹
        self.clear_file()
        # # 登录共享平台
        self.login()

        # # 从共享平台爬取数据
        # self.getDataFromWebPage()

        # # 登录数智财经管理平台
        # self.login_digital()
        # self.API_init()
        # # 新增账龄预警数据
        # self.addAlert()
        logger.info('账龄预警填报成功...')

    def clear_file(self):
        """
        root  # 当前目录路径
        dirs  # 当前路径下所有子目录
        files  # 当前路径下所有非目录子文件
        :return:
        """
        for root, dirs, files in os.walk(self.download_path):
            if not files:
                return
            for file in files:
                dir_path = os.path.join(self.download_path, file)
                os.remove(dir_path)

    def login(self):
        logger.info('登录共享作业平台开始')
        self.driver.get(self.url)
        # 输入用户名和密码
        self.fill_input('//input[@id="username"]', gx_username)
        self.fill_input('//input[@id="password"]', gx_password)
        self.click_element('//button[@class="ant-btn ant-btn-primary"]', mode='internal')
        time.sleep(1)

        app = QApplication(sys.argv)
        window = TWindow()
        window.show()
        time.sleep(3)
        # window.close()
        sys.exit(app.exec_())
        logger.info('登录共享作业平台成功')

    def getDataFromWebPage(self):
        """
        从网页爬取数据
        :return:
        """
        logger.info('从共享作业平台爬取数据开始')
        # trs = self.driver.find_element_by_css_selector("table tr")
        tr_xpath = '//span[text()="序号"]/../../../../../../../../div[2]/table/tbody/tr'
        # trs = self.find_elements(tr_xpath)
        # table tr
        data = []
        # for i in range(len(trs)):
        for i in range(1):
            confirm_review = {}
            for j in range(12):
                td = self.find_element(f"{tr_xpath}[{i + 1}]/td[{j + 1}]")
                # print(td.get_attribute('textContent'))
                if j == 0:
                    confirm_review['xh'] = td.get_attribute('textContent')
                elif j == 1:
                    confirm_review['khbm'] = td.get_attribute('textContent')
                elif j == 2:
                    confirm_review['khmc'] = td.get_attribute('textContent')
                elif j == 3:
                    confirm_review['hth'] = td.get_attribute('textContent')
                elif j == 4:
                    confirm_review['htmc'] = td.get_attribute('textContent')
                elif j == 5:
                    confirm_review['fph'] = td.get_attribute('textContent')
                elif j == 6:
                    confirm_review['fprq'] = td.get_attribute('textContent')
                elif j == 7:
                    confirm_review['bz'] = td.get_attribute('textContent')
                elif j == 8:
                    confirm_review['je'] = td.get_attribute('textContent')
                #     todo
                # elif j == 8:
                #     confirm_review['dkr'] = td.get_attribute('textContent')
                elif j == 9:
                    confirm_review['htfzr'] = td.get_attribute('textContent')
                #     发票下载
                elif j == 10:
                    pass
                #     合同下载
                elif j == 11:
                    self.click_element(f"{tr_xpath}[{i + 1}]/td[{j + 1}]/button")
                    time.sleep(0.5)
                    # self.driver.s
                    # 获得当前所有打开的窗口的句柄
                    all_handles = self.driver.window_handles
                    # print(len(all_handles))
                    oa_handle0 = all_handles[0]
                    oa_handle1 = all_handles[1]
                    # 切换待办页面
                    self.driver.switch_to.window(oa_handle1)
                    time.sleep(1)
                    keyboard.send_keys("^s")
                    time.sleep(3)
                    keyboard.send_keys("采购单.pdf")
                    time.sleep(1)
                    keyboard.send_keys('{ENTER}')
                    time.sleep(0.8)
                    self.driver.close()
                    time.sleep(1)
                    self.driver.switch_to.window(oa_handle0)
                    #  训练数据-采购单.pdf
                    confirm_review['htfj'] = os.path.join(self.download_path, '采购单.pdf')
                    # ActionChains(self.driver).send_keys(Keys.CONTROL, 's')
                # elif j == 10:
                #     confirm_review['fpfj'] = td.get_attribute('textContent')
                # elif j == 11:
                #     confirm_review['htfj'] = td.get_attribute('textContent')
            data.append(confirm_review)
        time.sleep(0.5)
        # print(data)
        self.filename = os.path.join(self.download_path, 'invoiceInfo.json')
        with open(self.filename, 'w') as file_obj:
            file_obj.write(json.dumps(data, ensure_ascii=False))

        logger.info('从共享作业平台爬取数据成功')

    def login_digital(self):
        logger.info('登录数智财经管理平台开始')
        self.driver.get(self.ARAP_URL)
        # 输入用户名和密码
        self.fill_input('//input[@id="username"]', cj_username)
        time.sleep(0.5)
        self.fill_input('//input[@id="password"]', cj_password)
        self.click_element('//button[@class="ant-btn ant-btn-primary"]', mode='internal')
        time.sleep(1)
        logger.info('登录数智财经管理平台成功')

    def addAlert(self):
        logger.info('新增应收开始')
        # 点击账龄预警超链接
        time.sleep(1)
        self.click_element('//a[contains(@href,"agingAlert")]', mode='internal')

        # 从Json文件中读取数据
        ys_list = self.getDataFromJsonFile()
        # print(ys_list)

        for ys_dict in ys_list:
            # 点击新增按钮
            time.sleep(0.5)
            self.click_element('//span[text()="新 增"]//parent::button', mode='internal')
            time.sleep(1)
            # 点击上传文件
            # 输入文件名上传影像
            self.click_element('//span[text()="点击上传"]//parent::button', mode='internal')
            title = self.get_html_title()
            windows = Desktop(backend='uia')
            win = windows[f'{title} - Google Chrome']
            # for root, dirs, files in os.walk(self.download_path):
            #     if not files:
            #         return
            #     for file in files:
            #         dir_path = os.path.join(self.download_path, file)
            if win.exists():
                editor = win.child_window(title="文件名(N):", control_type="Edit")
                editor.type_keys(ys_dict['htfj'], with_spaces=True)
                time.sleep(0.5)
                editor.type_keys("{ENTER}")

            # self.click_element('//span[text() = "取 消"]/..', mode='internal')
            time.sleep(1.1)
            # 输入客户编码
            self.fill_input("//input[@id = 'customerCode']", ys_dict['khbm'])
            # 输入客户名称
            time.sleep(0.9)
            self.fill_input("//input[@id = 'customerName']", ys_dict['khmc'])
            # 输入合同号
            time.sleep(0.9)
            self.fill_input("//input[@id = 'contractNumber']", ys_dict['hth'])
            # 输入合同名称
            time.sleep(0.9)
            self.fill_input("//input[@id = 'contractName']", ys_dict['htmc'])
            # 输入发票号
            time.sleep(0.9)
            self.fill_input("//input[@id = 'invoiceNumber']", ys_dict['fph'])
            # 输入发票日期
            time.sleep(0.9)
            self.click_element('//input[contains(@placeholder,"请选择发票日期")]', mode='internal')
            xpath = "//input[@class='ant-calendar-input ']"
            self.fill_input(xpath, ys_dict['fprq'])
            self.find_element(xpath).send_keys(Keys.ENTER)
            # 输入币种
            time.sleep(0.9)
            self.fill_input("//input[@id = 'currency']", ys_dict['bz'])
            # 输入金额
            time.sleep(0.9)
            self.fill_input("//input[@id = 'total']", ys_dict['je'])
            # 输入到款日 todo
            # time.sleep(0.8)
            # self.click_element('//input[contains(@placeholder,"请选择到款日")]', mode='internal')
            # xpath = "//input[@class='ant-calendar-input ']"
            # self.fill_input(xpath, ys_dict['dkr'])
            # self.find_element(xpath).send_keys(Keys.ENTER)

            # 输入合同负责人
            time.sleep(0.9)
            self.fill_input("//input[@id = 'contractPerson']", ys_dict['htfzr'])
            time.sleep(1)
            self.click_element('//span[text()="确 定"]//parent::button', mode='internal')

        logger.info('新增应收成功')

    def getDataFromJsonFile(self):
        """
        从json文件读取数据
        :return:
        """
        self.filename = os.path.join(self.download_path, 'invoiceInfo.json')
        with open(self.filename) as f:
            company_list = json.load(f)
        return company_list

    def get_html_title(self):
        title_xpath = 'html/head/title'
        ele = self.find_element(title_xpath)
        title = ele.get_attribute("textContent")
        return title

    def API_init(self):
        """
        初始化账龄预警数据
        :return:
        """
        try:
            params = {
                'contractNumber': 'HT010CBG009'
            }
            res_back = requests.get(INIT_URL, params=params)
            # print(res_back.json())

        except:
            # logger.error('接口调用失败')
            ...


if __name__ == '__main__':
    filename = os.path.join(ENVIRON_PATH)
    with open(filename) as f:
        environ_list = json.load(f)
        # print(environ_list)

    if not os.path.exists(environ_list.get("download_path")):
        os.mkdir(environ_list.get("download_path"))
    DownLoadPath = environ_list.get("download_path")
    if not os.path.exists(DownLoadPath):
        os.mkdir(DownLoadPath)

    # 根据配置文件执行运行环境
    if 'test' == environ_list.get('active'):
        ACTIVE = 'test'
    else:
        ACTIVE = 'dev'

    if 'test' == ACTIVE:
        # 共享作业平台
        SHARE_URL = 'http://172.30.10.154/arapshare/#/login'
        # 数智财经管理平台
        ARAP_URL = 'http://172.30.10.154/arapfinance/#/login'
        API_ADD_URL = f"http://172.30.10.154:32000/arap/receive/post/save"
        # 上传文件
        API_UPLOAD = f"http://172.30.10.154:32000/arap/file/upload"
        # RPA监听该接口，如果有返回值那么RPA就往下执行
        API_CONFIRM_URL = f"http://172.30.10.154:32000/arap/receive/get/rpa/list"
        # rpa状态同步接口
        API_SYNC_URL = f"http://172.30.10.154:32000/arap/receive/get/change/rpa/status"
        # 清除应收，还原待办接口
        API_CLEAR_URL = f"http://172.30.10.154:32000/arap/receive/get/clear"
        # 账龄预警数据初始化
        INIT_URL = f"http://172.30.10.154:32000/arap/agingWarning/get/init"
    elif 'dev' == ACTIVE:
        # 共享作业平台
        SHARE_URL = 'http://172.30.10.107/arapshare/#/login'
        # 数智财经管理平台
        # 登录
        ARAP_URL = 'http://172.30.10.107/arapfinance/#/login'
        # 新增数据
        API_ADD_URL = f"http://172.30.10.107:32000/arap/receive/post/save"
        # 上传文件
        API_UPLOAD = f"http://172.30.10.107:32000/arap/file/upload"
        # RPA监听该接口，如果有返回值那么RPA就往下执行
        API_CONFIRM_URL = f"http://172.30.10.107:32000/arap/receive/get/rpa/list"
        # rpa状态同步接口
        API_SYNC_URL = f"http://172.30.10.107:32000/arap/receive/get/change/rpa/status"
        # 清除应收，还原待办接口
        API_CLEAR_URL = f"http://172.30.10.107:32000/arap/receive/get/clear"
        # 账龄预警数据初始化
        INIT_URL = f"http://172.30.10.107:32000/arap/agingWarning/get/init"
    b = True
    while b:
        content = input('账龄预警开始执行(y/n)? ')
        if 'n' == content:
            logger.info('退出程序！')
            b = False
            time.sleep(1)
            sys.exit()
        elif 'y' == content:
            # app = QApplication(sys.argv)
            # window = TWindow()
            # window.show()
            zlyj = Zlyj(share_url=SHARE_URL, arap_url=ARAP_URL, download_path=DownLoadPath, environ_list=environ_list)
            zlyj.run()
            # sys.exit(app.exec_())
